/* eslint-disable @typescript-eslint/no-explicit-any */
import React, {
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
} from 'react'
import { observer } from 'mobx-react'
import {
  Upload,
  App,
  Progress,
  Image,
  UploadFile,
  UploadProps,
  Modal,
} from 'antd'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons'
import COS from 'cos-js-sdk-v5'
import COSStore from '../stores/COSStore'

export interface TencentCOSUploadRef {
  getUploadedFiles: () => UploadFile[]
  clearFiles: () => void
}
interface Props {
  maxCount?: number
  isContract?: boolean // 是否为合同上传模式
}

const TencentCOSUpload: React.FC = observer(
  forwardRef<TencentCOSUploadRef, Props>(
    ({ maxCount = 9, isContract = false }, ref) => {
      const { message } = App.useApp()
      const [fileList, setFileList] = useState<UploadFile[]>([])
      const [uploading, setUploading] = useState(false)
      const [progressVisible, setProgressVisible] = useState(false)
      const [progress, setProgress] = useState(0)
      const [previewVisible, setPreviewVisible] = useState(false)
      const [previewMedia, setPreviewMedia] = useState<{
        url: string
        type: 'image' | 'video' | 'contract'
      } | null>(null)

      useImperativeHandle(ref, () => ({
        getUploadedFiles: () => fileList.filter((f) => f.status === 'done'),
        clearFiles: () => setFileList([]),
      }))

      // 初始化时检查cos配置
      useEffect(() => {
        if (!COSStore.isReady && !COSStore.isLoading && !COSStore.error) {
          COSStore.init()
        }
      }, [])

      // 自定义上传请求
      const customRequest: UploadProps['customRequest'] = async (options) => {
        const { file, onProgress, onSuccess, onError } = options
        if (!COSStore.isReady) {
          onError?.(new Error('COS配置未加载'))
          message.error('COS配置未加载')
          return
        }

        try {
          setUploading(true)
          setProgressVisible(true)

          const cos = new COS({
            getAuthorization: (_options, callback) => {
              if (!COSStore.config) {
                callback(new Error('COS配置未加载'))
                return
              }
              callback({
                TmpSecretId: COSStore.config.tmpSecretId!,
                TmpSecretKey: COSStore.config.tmpSecretKey!,
                SecurityToken: COSStore.config.sessionToken!,
                ExpiredTime: parseInt(COSStore.config.expiredTime!),
                StartTime: parseInt(COSStore.config.startTime!),
              })
            },
          })

          const key = `uploads/${Date.now()}-${file.name}`

          cos.putObject(
            {
              Bucket: COSStore.config!.bucket!,
              Region: COSStore.config!.region!,
              Key: key,
              Body: file,
              onProgress: (progressData) => {
                const percent = Math.round(progressData.percent * 100)
                setProgress(percent)
                onProgress?.({ percent })
              },
            },
            (err, data) => {
              setUploading(false)
              setProgressVisible(false)
              if (err) {
                onError?.(err)
                message.error(`上传失败:${err.message}`)
                setFileList((prev) =>
                  prev.filter((item) => item.uid !== file.uid)
                )
              } else {
                onSuccess?.(data, file)
                message.success('上传成功')
                setFileList((prev) =>
                  prev.map((item) => {
                    if (item.uid === file.uid) {
                      return {
                        ...item,
                        status: 'done',
                        url: `https://${data.Location}`,
                      }
                    }
                    return item
                  })
                )
              }
            }
          )
        } catch (error) {
          setUploading(false)
          setProgressVisible(false)
          onError?.(error as Error)
          message.error('上传失败')
        }
      }

      const beforeUpload: UploadProps['beforeUpload'] = (file: File) => {
        // 合同模式下只接受docx和pdf文件
        if (isContract) {
          const isDocx =
            file.type ===
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
            file.name.endsWith('.docx')
          const isPdf =
            file.type === 'application/pdf' || file.name.endsWith('.pdf')

          if (!isDocx && !isPdf) {
            message.error('请上传Word文档(.docx)或PDF文件(.pdf)')
            return false
          }
        } else {
          // 非合同模式下只接受图片和视频
          const isImage = file.type.startsWith('image/')
          const isVideo = file.type.startsWith('video/')
          if (!isImage && !isVideo) {
            message.error('请上传图片或视频文件')
            return false
          }
        }

        const maxSize = 50 * 1024 * 1024 // 50MB
        if (file.size > maxSize) {
          message.error('文件大小不能超过50MB')
          return false
        }
        return true
      }

      const handleChange: UploadProps['onChange'] = ({ fileList }) => {
        setFileList(fileList)
      }

      const handlePreview: UploadProps['onPreview'] = (file: UploadFile) => {
        if (!file.url) return

        // 判断是否为合同文件（docx或pdf）
        const isContractFile =
          isContract &&
          (file.name?.endsWith('.docx') ||
            file.name?.endsWith('.pdf') ||
            file.type === 'application/pdf' ||
            file.type ===
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document')

        if (isContractFile) {
          // 合同文件在新标签页打开
          window.open(file.url, '_blank')
        } else {
          // 图片和视频使用Modal预览
          setPreviewMedia({
            url: file.url!,
            type: file.type?.startsWith('image/') ? 'image' : 'video',
          })
          setPreviewVisible(true)
        }
      }
      // 关闭预览
      const handleCancelPreview = () => {
        setPreviewVisible(false)
        setPreviewMedia(null)
      }

      const uploadButton = (
        <div>
          {COSStore.isLoading ? <LoadingOutlined /> : <PlusOutlined />}
          <div style={{ marginTop: 8 }}>
            {COSStore.isLoading
              ? '加载配置中...'
              : isContract
                ? `上传合同文件(${fileList.length}/${maxCount})`
                : `上传图片/视频(${fileList.length}/${maxCount})`}
          </div>
        </div>
      )

      if (COSStore.error) {
        return <div className="text-red-500">COS配置错误: {COSStore.error}</div>
      }

      return (
        <div>
          <Upload
            listType="picture-card"
            fileList={fileList}
            onChange={handleChange}
            customRequest={customRequest}
            onPreview={handlePreview}
            beforeUpload={beforeUpload}
            multiple={true}
            accept={
              isContract
                ? '.docx,.pdf,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                : 'image/*,video/*'
            }
            disabled={uploading || !COSStore.isReady}
          >
            {fileList.length >= maxCount ? null : uploadButton}
          </Upload>
          {progressVisible && (
            <div className="mt-4 w-full">
              <Progress percent={progress} status="active" />
              <div style={{ marginTop: 8 }}>
                正在上传{' '}
                {fileList.filter((f) => f.status === 'uploading').length}{' '}
                个文件...
              </div>
            </div>
          )}

          <Image.PreviewGroup>
            {fileList
              .filter((f) => f.status === 'done')
              .map((file) => (
                <Image
                  key={file.uid}
                  src={file.url}
                  width={100}
                  style={{ display: 'none' }}
                />
              ))}
          </Image.PreviewGroup>

          {/* 媒体预览模态框 */}
          <Modal
            open={previewVisible}
            title={previewMedia?.type === 'video' ? '视频预览' : '图片预览'}
            footer={null}
            onCancel={handleCancelPreview}
            width={previewMedia?.type === 'video' ? '80%' : 'auto'}
            destroyOnClose
          >
            {previewMedia &&
              (previewMedia.type === 'video' ? (
                <video controls autoPlay style={{ width: '100%' }}>
                  <source src={previewMedia.url} type="video/mp4" />
                  您的浏览器不支持视频播放
                </video>
              ) : (
                <Image
                  src={previewMedia.url}
                  style={{ maxWidth: '100%' }}
                  preview={false}
                />
              ))}
          </Modal>
        </div>
      )
    }
  )
)

export default TencentCOSUpload
